package com.un.ebs.order.service.impl;

import com.un.ebs.core.util.SecurityUtils;
import com.un.ebs.order.domain.Order;
import com.un.ebs.order.dto.OrderVo;
import com.un.ebs.order.service.OrderExpireService;
import com.un.ebs.order.service.OrderService;
import com.un.ebs.sys.base.QueueTaskListener;
import com.un.ebs.sys.base.QueueTaskService;
import com.un.ebs.sys.service.DelayedQueueService;
import com.un.ebs.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * </p>
 *
 * @author liubo
 * @create 2021-03-29 17:33
 */
@Service
public class OrderExpireServiceImpl implements OrderExpireService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private DelayedQueueService delayedQueueService;

    @Autowired
    private UserService userService;

    @Override
    public void sendTask(Order task, Long sec) {
        delayedQueueService.sendQueue(task,sec, TimeUnit.HOURS);
    }

    @Override
    public QueueTaskListener<Order> listener() {
        return new QueueTaskListener<Order>() {
            @Override
            public void invoke(Order task) {
                OrderVo obj = orderService.queryById(task.getId());
                if(!obj.getSubmitStatus()){
                    return;
                }

                if((obj.getExpireDay()<=-1 && (Integer.valueOf(obj.getExpireDefaultDay()))>0) || (obj.getRealMinMoney()>obj.getRealMoney())){
                    SecurityUtils.setUserContent(userService.markUserContext(obj.getSubmitUserId(), task.getTenantId(), null));
                    orderService.submitCancel(task.getId(),"没有在有效期内支付订金或全款，系统自动取消。");
                }

            }
        };
    }
}
